package 深市_沪市;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import Utils.Tools;

public class ClassifyFile {
    /**
     * 对所有的文件，按日期进行分类
     */

    static final String INPUT_PATH = "D:\\测试临时文件\\深市_沪市\\深圳";
    static final String OUTPUT_PATH = "D:\\测试临时文件\\深市_沪市\\深市_分类";


    public static void main(String[] args) {
        List<String> srcPathList = Tools.getAllFilePath(INPUT_PATH);
        Map<String, List<String>> standardMap = getStandardMap(srcPathList);
        standardMap.forEach((fileDate, filePaths) -> {
            classifyFile(fileDate, filePaths);
        });
    }

    public static void classifyFile(String fileDate, List<String> filePaths){
        String destFolder = OUTPUT_PATH + File.separator + fileDate;
        Tools.initFolder(destFolder);
        filePaths.forEach(filePath -> {
            File srcFile = new File(filePath);
            File destFile = new File(destFolder + File.separator + srcFile.getName());
            try {
                Files.copy(srcFile.toPath(), destFile.toPath());
                System.out.println(filePath + " -> " + destFile.toPath());
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    public static Map<String, List<String>> getStandardMap(List<String> filePaths){
        /**
         * 日期为key   所有这一天的文件路径组成list为val
         */
        Map<String, List<String>> resMap = new HashMap<>();

        for (String filePath: filePaths){
            String fileDate = getFileDate(filePath);

            if (!resMap.containsKey(fileDate))
                resMap.put(fileDate, new ArrayList<String>());
            resMap.get(fileDate).add(filePath);
        }

        return resMap;
    }


    public static String getFileDate(String filePath){
        /**
         * 从文件的绝对路径中提取文件日期
         */
        int symbolIndex = filePath.lastIndexOf("_");
        return filePath.substring(symbolIndex+1, filePath.length()-4);
    }


}
